<template>
  <div class="home">
   <ul>
      <li v-for="item in msgList" :key='item.id'>
        <p >
          <span>{{item.user}}            </span>
          <span>{{item.dateTime}}</span>
        </p>
        <p>消息:{{item.msg}}</p>
      </li>
    </ul>
   <input type="text" placeholder="请输入消息" v-model="msg">
   <button @click="sendMsg">发送消息</button>
  </div>
</template>

<script>


export default {
  name: 'Home',
  data(){
    return{
        msg:"",
      username:"",
      msgList:[],
      ws:null,  //建立连接
      lockReconnect:false,  //是否真正连接
      timeout:30*1000, //30秒一次心跳
      timeoutObj:null, //心跳倒计时
      serverTimeoutObj:null, //心跳倒计时
      timeoutnum:null, //断开  重连倒计时
    }
  },
  mounted () {
    this.data()
    this.initWebsocket()
     this.username = localStorage.getItem('username')
    if(!this.username){
      this.$router.push('/')
      return
    }
  },
  created () {
    
  },
  methods: {
    sendMsg(){
      let msg = this.msg
      if(!msg.trim().length){
        return
      }
      this.ws.send(JSON.stringify({
        id:new Date().getTime(),
        user:this.username,
        dateTime:new Date().toLocaleTimeString(),
        msg:this.msg
      }))
      this.msg = ''
    },
    data(){
       let now= new Date();
       console.log(now);
			let _month = ( 10 > (now.getMonth()+1) ) ? '0' + (now.getMonth()+1) : now.getMonth()+1;
			let _day = ( 10 > now.getDate() ) ? '0' + now.getDate() : now.getDate();
		let _hour = ( 10 > now.getHours() ) ? '0' + now.getHours() : now.getHours();
			let _minute = ( 10 > now.getMinutes() ) ? '0' + now.getMinutes() : now.getMinutes();
			let _second = ( 10 > now.getSeconds() ) ? '0' + now.getSeconds() : now.getSeconds();
       console.log(now.getFullYear());
      return now.getFullYear() + '-' + _month + '-' + _day + ' ' + _hour + ':'+ _minute + ':'+ _second;
     
    },
    initWebsocket(){
      this.ws = new WebSocket('ws://localhost:8888')
      this.ws.onopen = this.onopen;
      this.ws.onmessage = this.onmessage;
      this.ws.onclose = this.onclose;
      this.ws.onerror = this.onerror; 
    },
    //重新连接事件
    reconnect(){
      let that = this;
      if(that.lockReconnect){
        return;
      }
      that.lockReconnect = true
      //没连接上会一直重连，设置延迟避免请求过多
      that.timeoutnum && clearTimeout(that.timeoutnum)
      that.timeoutnum = setTimeout(()=>{
        that.initWebsocket()
        that.lockReconnect = false;
      },5000)
    },
    //重置心跳
    reset(){
      let that = this
      clearTimeout(that.timeoutObj)
      clearTimeout(that.serverTimeoutObj)
      that.start() //重启心跳
    },
    // 开始心跳
    start(){
      let that = this
      that.timeoutObj && clearTimeout(that.timeoutObj)
      that.serverTimeoutObj && clearTimeout(that.serverTimeoutObj)
      that.timeoutObj = setTimeout(()=>{
        //这里发送一个心跳，后端收到后，返回一个心跳消息
        if(that.ws.readyState == 1){
          // that.ws.send(JSON.stringify({
          //   data:{
          //     messageType:'heartCheck'
          //   }
          // }))
          console.log('websocket的链接已建立');
        }else{
          //否则重连
          console.log(9999);
          if(that.$route.path == '/index'){
            console.log('失败了');
            that.reconnect()
          }
        }
        that.serverTimeoutObj = setTimeout(()=>{
          that.ws.close()  //超时关闭
        },that.timeout)
      },that.timeout)
    },
    onopen(){
      console.log('连接成功');
      this.start()  //开始心跳
    },
    onmessage(e){
      console.log(e);
       let msg = JSON.parse(e.data)
       this.msgList.push(msg)
      this.reset()  //收到服务器信息，心跳重置
    },
    onclose(){
      // console.log('连接关闭');
      this.reconnect()  //重连
    },
    onerror(){
      console.log('出现错误');
      this.reconnect()
    }
  }
}
</script>
<style scoped>
li{
  list-style: none;
}
p,span{
  text-align: left;
}
</style>